<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片 -->
    <el-card>
        <!-- 添加一行，放一个添加按钮 -->
        <el-row :gutter="10">
            <el-col :span="6">
                <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
            </el-col>
        </el-row>

        <!-- 角色列表区 -->
        <el-table :data="rolesList" style="width: 100%">
            <!-- 展开列 -->
            <el-table-column type="expand">
                <!-- 作用域插槽这一行scope.row能拿到所有的权限 -->
                <template slot-scope="scope">
                    <!-- 一级 -->
                    <el-row :class="['bdbottom','centercol',index1===0?'bdtop':'']" v-for="(item1,index1) in scope.row.children" :key="item1.id">
                        <el-col :span="5">
                            <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <el-col :span="19">
                            <!-- 二级 -->
                            <el-row :class="['centercol',index2===0?'':'bdtop']" v-for="(item2,index2) in item1.children" :key="item2.id">
                                <el-col :span="6">
                                    <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="18">
                                    <!-- 三级 -->
                                    <el-row :class="[index3===0?'':'bdtop']" v-for="(item3,index3) in item2.children" :key="item3.id">
                                        <el-col>
                                            <el-tag type="warning" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                            <i class="el-icon-caret-right"></i>
                                        </el-col>
                                    </el-row>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="roleName" label="角色名称"></el-table-column>
            <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <!-- 本来是点击编辑后，角色修改对话框显示的，但是需要获取该角色的信息，所以在函数里先显示，再做其他处理 -->
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditRoleDialog(scope.row.id)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(scope.row.id)">删除</el-button>
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialogVisible(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 添加角色对话框 -->
        <el-dialog
        title="添加角色"
        :visible.sync="addRoleDialogVisible"
        width="50%"
        @close="addRoleDialogClosed">
            <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="addRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="addRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="addRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRole">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改角色对话框 -->
        <el-dialog
        title="修改角色"
        :visible.sync="editRoleDialogVisible"
        width="50%"
        @close="editRoleDialogClosed">
            <el-form :model="editRoleForm" :rules="editRoleFormRules" ref="editRoleFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer">
                <el-button @click="editRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRoleInfo">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配权限对话框 -->
        <el-dialog
        title="分配权限"
        :visible.sync="setRightDialogVisible"
        width="50%">
        <!-- 树形控件 (绑定复选框，每次选的值是id)-->
            <el-tree :data="rightList" :props="treeProps" show-checkbox node-key="id" 
            default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </span>
        </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
    data(){
        return{
            // 角色列表
            rolesList:[],
            // 添加角色对话框
            addRoleDialogVisible:false,
            // 添加角色表单
            addRoleForm:{
                roleName:'',
                roleDesc:''
            },
            // 添加角色表单的验证规则
            addRoleFormRules:{
                roleName:[
                    {required: true, message: '请输入角色名称', trigger: 'blur' },
                    {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
                ],
                roleDesc:[
                    {required: true, message: '请输入角色名称', trigger: 'blur' },
                    {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
                ]
            },

            // 修改角色对话框
            editRoleDialogVisible:false,
            // 修改角色表单是从数据库中查询到的
            editRoleForm:{
            },
            // 修改角色表单的验证规则
            editRoleFormRules:{
                roleName:[
                    {required: true, message: '请输入角色名称', trigger: 'blur' },
                    {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
                ],
                roleDesc:[
                    {required: true, message: '请输入角色名称', trigger: 'blur' },
                    {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
                ]
            },

            // 控制分配权限对话框的显示与隐藏
            setRightDialogVisible:false,
            // 权限列表
            rightList:[],
            // 树形控件的属性绑定对象
            treeProps:{
                // 看到的是哪个属性对应的值
                label:'authName',
                // 父子之间通过什么属性嵌套的
                children:'children'
            },
            // 存储三级权限
            defKeys:[],
            // 当前即将分配角色的id
            roleId:''
        }
    },
    created(){
        this.getRolesList();
    },
    methods:{
        // 获取角色列表
        async getRolesList(){
            const {data:res} = await this.$http.get('roles');
            if(res.meta.status!==200) return this.$message.error('获取用户列表失败');
            this.rolesList=res.data;
            console.log(this.rolesList)
        },
        // 添加角色对话框关闭时触发
        addRoleDialogClosed(){
            this.$refs.addRoleFormRef.resetFields();
        },
        // 添加角色(需要先预验证)
         addRole(){
            this.$refs.addRoleFormRef.validate(async valid=>{
                if(!valid) return;
                const {data:res} = await this.$http.post('roles',this.addRoleForm);
                if(res.meta.status!==201) return this.$message.error('添加角色失败');
                this.$message.success('添加角色成功');
                this.addRoleDialogVisible = false;
                this.getRolesList();
            })
        },

        // 查询需要修改的角色
        async showEditRoleDialog(id){
            const{data:res} = await this.$http.get(`roles/${id}`);
            if(res.meta.status!==200) return this.$message.error('需要修改的角色获取失败');
            this.editRoleForm = res.data;
            this.editRoleDialogVisible = true;
        },
        // 修改角色对话框关闭时触发
        editRoleDialogClosed(){
            this.$refs.editRoleFormRef.resetFields();
        },
        // 点击确定时触发修改角色信息(需要先预验证)
        editRoleInfo(){
            this.$refs.editRoleFormRef.validate(async valid=>{
                if(!valid) return;
                const{data:res} = await this.$http.put(`roles/${this.editRoleForm.roleId}`,{
                    roleName:this.editRoleForm.roleName,
                    roleDesc:this.editRoleForm.roleDesc
                })
                if(res.meta.status!==200) return this.$message.error('更新角色失败');
                this.editRoleDialogVisible = false;
                this.getRolesList();
                this.$message.success('更新角色成功');
            })
        },
        // 删除角色
        async removeRoleById(id){
            const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err);

            if(confirmResult!=='confirm') return this.$message.info('已取消删除角色')

            const {data:res} = await this.$http.delete(`roles/${id}`);
            if(res.meta.status!==200) return this.$message.error('删除角色失败');
            this.getRolesList();
            this.$message.success('删除角色成功');
        },

        // 删除标签
        async removeRightById(role,rightId){
            const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)

            if(confirmResult!=='confirm'){
                return this.$message.info('已取消删除')
            }

            const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
            if(res.meta.status!==200) return this.$message.error('删除权限失败');

            /*  每删除一个标签，权限都会关闭，因为每次删除后返回的data都是还留下的权限
             为了防止每次删除权限后都会合上，需要我们把角色的children(权限)重新赋值为返回的数据，增强体验感 */
            role.children = res.data;
            return this.$message.success('删除权限成功');
        },
        // 递归函数用于获取当前角色下的三级权限的Id，保存在数组中
        getLeafKeys(node,arr){
            // 如果当前Node节点不包含children属性，则是三级节点
            if(!node.children){
                return arr.push(node.id);
            }
            node.children.forEach(item => {
                this.getLeafKeys(item,arr);
            });
        },

        // 展示分配权限对话框并获取权限列表
        async showSetRightDialogVisible(role){
            this.roleId = role.id;
            const {data:res} = await this.$http.get(`rights/tree`);
            if(res.meta.status!==200) return this.$message.error('获取权限列表失败');
            this.rightList = res.data;
            console.log(this.rightList);
            // 获取三级节点的id
            this.getLeafKeys(role,this.defKeys);
            this.setRightDialogVisible = true;
        },
        
        // 为角色分配权限
        async allotRights(){
            const checkedKeys = [...this.$refs.treeRef.getCheckedKeys(),...this.$refs.treeRef.getHalfCheckedKeys()];
            const nodeStr = checkedKeys.join(',');


            const{ data:res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids:nodeStr});
            if(res.meta.status!==200) return this.$message.error('分配权限失败');
            // 分配成功后，刷新角色列表，提示成功，隐藏对话框
            this.getRolesList();
            this.$message.success('分配角色成功');
            this.setRightDialogVisible = false;
        }

    }
}
</script>

<style lang="less" scoped>
    .el-tag{
        margin: 7px;
        margin-left: 50px;
    }
    .bdbottom{
        border-bottom: 1px solid #eee;
    }
    .bdtop{
        border-top:1px solid #eee;
    }
    .centercol{
        display: flex;
        align-items: center;
    }
</style>